﻿using Aribaccio.Office;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 检测记录视图模型类
    /// </summary>
    public partial class DetectRecordViewModel : PagerViewModel<TDetectRecordData, UserControl>
    {
        /// <summary>
        /// 导入导出文件辅助类接口[目前csv\excel]
        /// </summary>
        protected IOfficer Officer { get; set; }
        /// <summary>
        /// 工位管理实例
        /// </summary>
        protected DetectRecordManager DetectRecordMgr { get; set; }

        /// <summary>
        /// 检测检测记录状态
        /// </summary>
        [ObservableProperty]
        protected DetectResultStatus detectStatus;
        /// <summary>
        /// 查询起始日期
        /// </summary>
        [ObservableProperty]
        protected DateTime queryStartDate;
        /// <summary>
        /// 查询结束日期
        /// </summary>
        [ObservableProperty]
        protected DateTime queryEndDate;
        /// <summary>
        /// 查询当前工位
        /// </summary>
        [ObservableProperty]
        protected MStation? stationItem;
        /// <summary>
        /// 查询工位集合
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MStation> stationItems;

        /// <summary>
        /// 构造函数[注入]
        /// </summary>
        public DetectRecordViewModel(DetectRecordManager argDetectRecordManager)
            : base(20)
        {
            this.DetectRecordMgr = argDetectRecordManager;
            this.DetectStatus = DetectResultStatus.None;
            this.QueryStartDate = DateTime.Today;
            this.QueryEndDate = DateTime.Today;
            this.StationItems = new ObservableCollection<MStation>();
            this.Officer = new OfficerCsv();
        }

        /// <summary>
        /// 初始化加载查询选项数据集
        /// </summary>
        /// <returns></returns>
        protected async Task InitLoadItems()
        {
            await Task.Factory.StartNew(() =>
            {
                //初始化工位数据
                var stations = this.DetectRecordMgr.GetStations();
                foreach (var item in stations)
                {
                    if (item.ID <= 0) continue;
                    this.StationItems.Add(item);
                }
                this.StationItem = this.StationItems.FirstOrDefault();
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }

        /// <summary>
        /// 页面初始化加载事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteLoaded()
        {
            if (this.IsLoaded) return;
            //获取查询选项数据集
            var resultTask = this.InitLoadItems();
            await resultTask.ConfigureAwait(false);

            //最后标记初始化加载完成
            this.IsLoaded = true;
            //初始化查询数据
            resultTask = this.ExecuteQuery();
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 查询事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteQuery()
        {
            if (this.StationItem == null) return;
            this.IsExecutedIdle = false;
            QueryRecordDto queryData = new QueryRecordDto()
            {
                StationType = this.StationItem.StationType,
                StartDateTime = this.QueryStartDate,
                EndDateTime = this.GetMidnightDateTime(this.QueryEndDate),
                Status = this.DetectStatus
            };
            var resultTask = this.QueryData(queryData);
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 导出事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteExport()
        {
            if (this.PagerData == null || this.PagerData.ItemsSource.Count <= 0) return;
            try
            {
                this.IsExecutedIdle = false;
                string strPathFullName = SelectOutputPath();
                if (string.IsNullOrEmpty(strPathFullName)) return;

                await this.Officer.WriteDataModelHead<TDetectRecordData>(strPathFullName, this.PagerData.ItemsSource.ToList());
                //成功后，打开导出文件存储路径
                System.Diagnostics.Process.Start("Explorer", $@"/select,{strPathFullName}");
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 传输变更数据
        /// </summary>
        /// <typeparam name="TData">泛型</typeparam>
        /// <param name="argData">传递数据</param>
        public override void TransferChangeData<TData>(TData argData) where TData : class
        {
            if (argData == null) return;
            if (!(argData is QueryRecordDto queryData)) return;

            //更新显示查询条件
            this.IsExecutedIdle = false;
            this.QueryStartDate = queryData.StartDateTime.Date;
            this.QueryEndDate = queryData.EndDateTime.Date;
            this.DetectStatus = queryData.Status;
            this.StationItem = this.StationItems.FirstOrDefault(v => v.StationType == queryData.StationType);
            //查询数据
            _ = this.QueryData(queryData);
        }

        /// <summary>
        /// 查询检测记录
        /// </summary>
        protected async Task QueryData(QueryRecordDto argQueryData)
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    var DetectRecordDatas = this.DetectRecordMgr.QueryDetectRecordData(argQueryData);
                    var sourceItems = DetectRecordDatas != null ? DetectRecordDatas : new List<TDetectRecordData>();
                    base.InitCreateItems(new ObservableCollection<TDetectRecordData>(sourceItems));
                }
                finally
                {
                    this.IsExecutedIdle = true;
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }

        /// <summary>
        /// 选择输出路径
        /// </summary>
        protected string SelectOutputPath()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog() { AddExtension = true };
            // 设置文件类型过滤器
            saveFileDialog.Filter = "CSV Data(*.csv)|*.csv";
            // 设置默认文件名
            saveFileDialog.FileName = $"BDP_DetectRecord_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.csv";
            string strFilePath = string.Empty;
            if (saveFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                strFilePath = saveFileDialog.FileName;
            }
            return strFilePath;
        }

        /// <summary>
        /// 获取日期的午夜时间点
        /// </summary>
        /// <param name="dateTime">原日期时间</param>
        /// <returns></returns>
        protected DateTime GetMidnightDateTime(DateTime dateTime)
        {
            //dateTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999).AddMicroseconds(999);
            return dateTime.Date.Add(GlobalDefine.MidnightTimeSpan);
        }
    }
}
